package com.game.chessgame;

public class Board {
    private Piece[][] board;
    private Player currentPlayer;

    public Board() {
        board = new Piece[8][8];
        currentPlayer = Player.WHITE;
    }

    public void initialize() {
        // 初始化棋盘
        for (int i = 0; i < 8; i++) {
            board[1][i] = new Pawn(Player.BLACK);
            board[6][i] = new Pawn(Player.WHITE);
        }

        board[0][0] = new Rook(Player.BLACK);
        board[0][7] = new Rook(Player.BLACK);
        board[0][1] = new Knight(Player.BLACK);
        board[0][6] = new Knight(Player.BLACK);
        board[0][2] = new Bishop(Player.BLACK);
        board[0][5] = new Bishop(Player.BLACK);
        board[0][3] = new Queen(Player.BLACK);
        board[0][4] = new King(Player.BLACK);

        board[7][0] = new Rook(Player.WHITE);
        board[7][7] = new Rook(Player.WHITE);
        board[7][1] = new Knight(Player.WHITE);
        board[7][6] = new Knight(Player.WHITE);
        board[7][2] = new Bishop(Player.WHITE);
        board[7][5] = new Bishop(Player.WHITE);
        board[7][3] = new Queen(Player.WHITE);
        board[7][4] = new King(Player.WHITE);
    }

    public void printBoard() {
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                if (board[i][j] == null) {
                    System.out.print(". ");
                } else {
                    System.out.print(board[i][j].getSymbol() + " ");
                }
            }
            System.out.println();
        }
    }

    public boolean movePiece(String from, String to) {
        int fromX = from.charAt(0) - 'a';
        int fromY = 8 - (from.charAt(1) - '0');
        int toX = to.charAt(0) - 'a';
        int toY = 8 - (to.charAt(1) - '0');

        if (fromX < 0 || fromX >= 8 || fromY < 0 || fromY >= 8 || toX < 0 || toX >= 8 || toY < 0 || toY >= 8) {
            return false;
        }

        Piece piece = board[fromY][fromX];
        if (piece == null || piece.getPlayer() != currentPlayer) {
            return false;
        }

        if (piece.canMove(fromX, fromY, toX, toY, board)) {
            board[toY][toX] = piece;
            board[fromY][fromX] = null;
            currentPlayer = (currentPlayer == Player.WHITE) ? Player.BLACK : Player.WHITE;
            return true;
        }

        return false;
    }
}